package com.example.market.controller;

import com.example.market.entity.Employee;
import com.example.market.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeHandler {
    @Autowired
    private EmployeeRepository employeeRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Employee> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return employeeRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody Employee employee){
        Employee result = employeeRepository.save(employee);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Employee findById(@PathVariable("id") Integer eno){
        return employeeRepository.findById(eno).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Employee employee){
        Employee result = employeeRepository.save(employee);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer eno){
        employeeRepository.deleteById(eno);
    }

    @GetMapping("/login/{ename}/{epassword}")
    public String login(@PathVariable("ename") String ename,@PathVariable("epassword") String epassword) { //账号密码查询
        Employee result = employeeRepository.findByEnameAndEpassword(ename, epassword);
        if(result != null) {
            return "success";
        }else {
            return "error";
        }
    }
}
